package com.peanut.baby.mvp.trend.publish;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.db.DBManager;
import com.peanut.baby.model.BBSMoment;
import com.peanut.baby.model.Photo;
import com.peanut.baby.model.Task;
import com.peanut.baby.model.TaskDBRecord;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.mvp.bbs.BBSBaseActivity;
import com.peanut.baby.util.TagUtil;
import com.peanut.devlibrary.RequestResult;
import com.peanut.devlibrary.picker.ImageConfig;
import com.peanut.devlibrary.picker.PhotoPickerActivity;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.util.TimeUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.richeditor.RichEditor;

/**
 * Created by anonymouslystudio on 2017/7/28.
 */

public class TrendPublishActivity extends BBSBaseActivity implements TrendPublishContract.View,
        View.OnClickListener,RichEditor.OnTextChangeListener,TitleLayout.OnTitleClickListener{
    private static final String TAG = TrendPublishActivity.class.getSimpleName();
    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.publish_type)
    TextView publishType;
    @BindView(R.id.publish_edit_text)
    RichEditor editor;
    @BindView(R.id.publish_album)
    LinearLayout publishAlbum;

    public String content = "";

    private List<Photo> photos;

    private TrendPublishContract.Presenter presenter;

    private TaskDBRecord record;

    public static void start(Context ctx) {
        ctx.startActivity(new Intent(ctx, TrendPublishActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moment_publish);
        ButterKnife.bind(this);
        initViews();
        presenter = new TrendPublishPresenter(this,this);

        if(InitManager.getInstance().getUser() != null){
            record = DBManager.getInstance().getTaskRecord(Integer.parseInt(InitManager.getInstance().getUserId()), TimeUtil.getCurrentDate());
        }
    }

    private void initViews(){
        title.setOnTitleClickedListener(this);
        title.setTitle("发布动态");
        title.setTitleRightText("提交");
        title.setTitleRightVisibility(true);

        editor.setEditorFontColor(getResources().getColor(R.color.text_dark));
        editor.setFontSize(14);
        editor.setPadding(10, 10, 10, 10);
        editor.setPlaceholder("请添加文字和图片，字数不超过200个.");
        editor.setOnTextChangeListener(this);
        editor.loadCSS("file:///android_asset/img.css");

        publishType.setOnClickListener(this);
        publishAlbum.setOnClickListener(this);
        photos = new ArrayList<>();
    }

    @Override
    public void onPicturePermissionGranted() {
        PhotoPickerActivity.startForResult(TrendPublishActivity.this, 1, true, PhotoPickerActivity.MODE_SINGLE, new ImageConfig());
    }

    @Override
    public void onPicturePermissionDenied() {

    }

    @Override
    public void onPictureUploadFinished(boolean success, String failReason, UploadConf successConfig) {
       dismissProgressDialog();
        if(success){
            insertImageWhenUploaded(successConfig);
        }else{
            showToast("图片上传失败: "+failReason);
        }
    }

    @Override
    public void onSendMomentSuccess(BBSMoment moment) {
        dismissProgressDialog();
        showToast("发送成功");
        if(record != null){
            record.sendMomentCount++;
            if(record.sendMomentCount > Task.MAX_NEW_MOMENTS){
                record.sendMomentCount = Task.MAX_NEW_MOMENTS;
            }
            DBManager.getInstance().updateTaskRecord(record);
        }
        finish();
    }

    @Override
    public void onSendMomentFailed(String reason) {
        dismissProgressDialog();
        showToast("发送失败 "+reason);
    }

    private void insertImageWhenUploaded(UploadConf config){
        Photo photo = new Photo();
        photo.path = config.localPath;
        photo.url = config.getResultFullUrl();
        photos.add(photo);
        Log.d(TAG,"insert image when uploaded b " +config.getResultFullUrl());
        if(!editor.isFocused()){
            editor.focusEditor();
        }
        editor.insertImage(config.getResultFullUrl(),config.bucketName);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RequestResult.REQUEST_CODE_PHOTOS:
                ArrayList<String> _photos = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                onPickPhotoResult(_photos.get(0));
                break;
        }
    }

    private void onPickPhotoResult(String result) {
        showProgressDialog("请稍后...",false);
        presenter.compressAndUploadPicture(result);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.publish_album:
                presenter.checkPicturePermission(TrendPublishActivity.this);
                break;
            case R.id.publish_type:
                new BaseDialog().showListDialog(this, "请选择类型", TagUtil.getTypeList(), new BaseDialog.OnListItemSelectedListener() {
                    @Override
                    public void onListItemSelected(String value) {
                        publishType.setText(value);
                    }
                });
                break;
        }
    }

    @Override
    public void onTextChange(String text) {
        content = text;

    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {
        Log.d(TAG,"content:\n"+content);

        String type = publishType.getText().toString().trim();
        if(StringUtil.isNullOrEmpty(type)){
            showToast("请选择动态类型");
            return;
        }
        if(StringUtil.isNullOrEmpty(content)){
            showToast("请填写动态内容");
            return;
        }
        Log.d(TAG,"content length: "+content.length()+"");
        String newstr = content.replaceAll("<[.[^>]]*>","");
        Log.d(TAG,"content length: "+newstr.length()+"");
        if(newstr.length() > 200){
            showToast("字数超过200啦！");
            return;
        }
        String pictures = getFixedPictureUrlCollections();
        showProgressDialog("请稍候...",false);
        presenter.submitMoment(content,type,pictures);

    }

    @Override
    public void onTitleClicked() {

    }

    private String getFixedPictureUrlCollections(){
        if(photos == null || photos.isEmpty()){
            return "";
        }
        int len = photos.size();
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<len;i++){
            Photo photo = photos.get(i);
            if(content.contains(photo.url)){
                sb.append(photo.url);
                sb.append(",");
            }
        }
        String result = sb.toString();
        if(result.endsWith(",")){
            result = result.substring(0,result.length()-1);
        }
        Log.d(TAG,"fixedPicCollections: "+result);
        return result;
    }
}
